/**
 * 
 */
package edu.towson.cosc.cosc455.elugonjic.compiler;
import java.util.ArrayList;

import edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer;

/**
 * @author elugon1
 *
 */
public class MyLexicalAnalyzer implements LexicalAnalyzer {

	private String input, newToken;
	private char[] lexeme;
	private char nextChar;
	private int lexLength, position, lexPos;
	private boolean reset = false; 
	
	public void start(String line){
		input = line;
		position = 0;
		lexPos = 0;
		lexeme = new char[input.length()];
		getCharacter();		
		getNextToken();		
	}
	
	public void getNextToken() {
		if(reset){
		lexLength = 0;
		lexPos = 0;
		}
		
		// Ignore spaces and add the first character to the token
		getNonBlank();
		addCharacter();

		// Continue gathering characters for the token
		while((nextChar != '\n') && (nextChar != ' ') && (!MyCompiler.lexicalTokens.getList().contains(newToken))){
			getCharacter();
			addCharacter();
		}			
		
		
		// Convert the gathered character array token into a String
		newToken = new String(lexeme);

		if(lookupToken()){
			MyCompiler.token = newToken.substring(0, lexLength - 1).toUpperCase();
			reset = true;			
		}
		else{
			reset = false;
			getNextToken();
		}
	}

	/* (non-Javadoc)
	 * @see edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer#getCharacter()
	 */
	@Override
	public void getCharacter() {
		if (position < input.length()){
			nextChar = Character.toUpperCase(input.charAt(position));
			position++;
			if(nextChar == '#'){
				lexLength = 0;
			lexPos = 0;}
		}
		else nextChar = '\n';
	}
	
	/* (non-Javadoc)
	 * @see edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer#addCharacter()
	 */
	@Override
	public void addCharacter() {
		lexeme[lexPos] = nextChar;
		lexPos++;
		lexLength++;
	}
	

	/* (non-Javadoc)
	 * @see edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer#isSpace(java.lang.Character)
	 */
	@Override
	public boolean isSpace(char c){
		if (c == ' ')return true;
		else return false;
	}

	/* (non-Javadoc)
	 * @see edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer#getNonBlank()
	 */
	private void getNonBlank(){
		while(isSpace(nextChar))
			getCharacter();
	}
	
	/* (non-Javadoc)
	 * @see edu.towson.cosc.cosc455.interfaces.LexicalAnalyzer#lookupToken()
	 */
	@Override
	public boolean lookupToken() {
		if(MyCompiler.lexicalTokens.getList().contains(newToken.substring(0, lexLength - 1)))
			return true;
		else return false;
	}

}
